package com.qujia.station.service.impl;

import com.qujia.common.exception.BaseException;
import com.qujia.station.domain.ActivityCommodityRules;
import com.qujia.station.domain.Commodity;
import com.qujia.station.domain.MarketActivity;
import com.qujia.station.enums.AllOrPartType;
import com.qujia.station.mapper.ActivityCommodityRulesMapper;
import com.qujia.station.service.ActivityCommodityRulesService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Objects;


@Service("activityCommodityRulesService")
@Slf4j
public class ActivityCommodityRulesServiceImpl implements ActivityCommodityRulesService {

    @Autowired
    private ActivityCommodityRulesMapper activityCommodityRulesMapper;


    @Override
    public ActivityCommodityRules selectCommodityDiscount(Commodity commodity, List<MarketActivity> marketActivityList) {
        if(Objects.isNull(commodity) || Objects.isNull(commodity.getCommodityId())){
            throw new BaseException("商品不存在, 无法获取商品优惠价格");
        }

        if(CollectionUtils.isEmpty(marketActivityList)){
            throw new BaseException("活动不存在，无法获取商品优惠价格");
        }
        ActivityCommodityRules rules = new ActivityCommodityRules();
        for (MarketActivity marketActivity : marketActivityList) {
            // 获取进行中最新的包含该商品优惠的活动规则 用于计算商品优惠价
            if(AllOrPartType.ALL.getValue().equals(marketActivity.getAllOrPart())){
                rules.setMarketActivityId(marketActivity.getMarketActivityId());
                rules.setCommodityId(commodity.getCommodityId());
                rules.setDiscountNum(marketActivity.getDiscountNum());
                // 选择全部商品没有特价

                rules.setMarketActivityType(marketActivity.getMarketActivityType());
                break;
            }
            // 部分商品
            List<ActivityCommodityRules> list = activityCommodityRulesMapper.selectActivityCommodityRulesByMarketActivityId(marketActivity.getMarketActivityId());
            if(CollectionUtils.isNotEmpty(list)){
                for (ActivityCommodityRules activityCommodityRules : list) {
                    if(commodity.getCommodityId().equals(activityCommodityRules.getCommodityId())){
                        BeanUtils.copyProperties(activityCommodityRules,rules);
                        rules.setMarketActivityType(marketActivity.getMarketActivityType());
                    }
                }
            }
            // 匹配到了优惠规则
            if(Objects.nonNull(rules.getCommodityId())){
                break;
            }
        }
        return rules;
    }
}
